package io.serialize_stream;

import java.io.*;

/*
java.io.NotSerializableException没有实现Serializable接口

java.io.InvalidClassException: io.serialize_stream.Student;

local class incompatible:
stream classdesc serialVersionUID = -3107967165734491621,
local class serialVersionUID = -5576336309167373835
 */
public class Demo01 {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //进行序列化操作
        serialize();

        //反序列化操作
        unSerialize();
    }

    private static void unSerialize() throws IOException, ClassNotFoundException {
        ObjectInputStream in = new ObjectInputStream(
                new FileInputStream("wzx.txt"));
        //readObject()
        Object o = in.readObject();
        System.out.println(o);
        //close
        in.close();
    }

    private static void serialize() throws IOException {
        //创建Student对象
        Student student = new Student("zx",23);
        //创建序列化流对象
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream("wzx.txt"));

        //writeObject(对象)
        out.writeObject(student);
        out.close();
    }
}
class Student implements Serializable {
    //序列化和反序列化要生成一个serialVersionUID
    @Serial
    private static final long serialVersionUID = -5576336309167373835L;
    String name;
    int age;
    int score;

    //显示声明serialVersionUID
    //static final long serialVersionUID = -3107967165734491621L;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student(String name, int age, int score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }

}
